package com.ruoyi.utils;

import com.ruoyi.annotation.BeanFieldType;
import com.ruoyi.annotation.FieldNotNull;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 判断实体类中字段不为空配合@FieldNotNull注解使用
 *
 * @author: Gao Tianle
 * @date: 2024-03-06 14:59
 **/
public class FieldNotNullUtil {

    public static void isValid(Object o) {
        //通过反射获取字段名
        List<String> tableFieldName = getBeanFieldName(o);
        for (String fieldName : tableFieldName) {
            //通过反射获取FieldNotNull注解的参数
            FieldNotNull beanFieldType = getTableFieldValue(o, fieldName);
            //为空不进行验证
            if (StringUtils.isNull(beanFieldType)) {
                continue;
            }
            // 构造get方法名
            String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
                    + fieldName.substring(1);
            try {
                // 获取get方法对象
                Method getMethod = o.getClass().getMethod(getMethodName);
                // 调用get方法获取值
                Object value = getMethod.invoke(o);
                if (StringUtils.isNull(value) || StringUtils.isEmpty(String.valueOf(value))) {
                    throw new ServiceException(beanFieldType.message());
                }
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取实体所有字段
     *
     * @param o
     * @return
     */
    private static List<String> getBeanFieldName(Object o) {
        List<String> stringList = new ArrayList<>();
        Field[] fields = o.getClass().getDeclaredFields();
        for (Field field : fields) {
            String fieldName = field.getName();
            stringList.add(fieldName);
        }
        return stringList;
    }

    /**
     * 获取字段注解
     *
     * @param main
     * @return
     */
    private static FieldNotNull getTableFieldValue(Object main, String label) {
        FieldNotNull beanFieldType = null;
        try {
            Field field = main.getClass().getDeclaredField(label);
            beanFieldType = field.getAnnotation(FieldNotNull.class);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return beanFieldType;
    }
}
